package com.example.dbRouting.router.impl;

import com.example.dbRouting.DbContextHolder;
import com.example.config.RouterConstants;
import com.example.dbRouting.db.RouterSet;
import com.example.dbRouting.router.DBRwRouter;
import com.example.dbRouting.router.RouterUtils;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description: TODO(根据指定变量动态切 库和表)
 * @author wangkai
 * @date 2018年5月31日
 *
 */
@Component
public class DBRwRouterImpl implements DBRwRouter {

	/**
	 * 配置列表
	 */
	private List<RouterSet> routerSetList;

	public List<RouterSet> getRouterSetList() {
		return routerSetList;
	}

	public void setRouterSetList(List<RouterSet> routerSetList) {
		this.routerSetList = routerSetList;
	}

	/*
	 * (non-Javadoc) 读写路由实现
	 * 
	 * @see com.sub.dbRouting.DBRwRouter#doRouteByResource(java.lang.String)
	 */
	@SuppressWarnings("static-access")
	@Override
	public String doRouteByResource(String resourceCode) {
		String dbkey = null;
		if (routerSetList != null && routerSetList.size() > 0) {
			RouterSet routerSet = routerSetList.get(0);
			if (resourceCode.equals(RouterConstants.ROUTER_TYPE_MASTER)) {
				dbkey = (String) routerSet.getDbKeyMap().get(0).get(RouterConstants.ROUTER_TYPE_MASTER);
				DbContextHolder.init().setDbKey(dbkey);
			} else if (resourceCode.equals(RouterConstants.ROUTER_TYPE_SLAVE)) {
				StringBuffer code = new StringBuffer(RouterConstants.ROUTER_TYPE_SLAVE);
				code.append(System.currentTimeMillis());
				int routeFieldInt = RouterUtils.getResourceCode(code.toString());
				int mode = routeFieldInt % (routerSet.getDbNumber() - 1);
				dbkey = (String) routerSet.getDbKeyMap().get(0).get(RouterConstants.ROUTER_TYPE_SLAVE + mode);
				DbContextHolder.init().setDbKey(dbkey);
			}
		}
		return dbkey;
	}

}
